import React, { Component } from 'react';
import './scss/ImportFile.scss';
import { LgButton, LgPopLayer, LgLoadingCircleRotation } from 'lancoo-web-ui';
import { message } from "antd";
import {
    getData,
    getRealPath,
} from "../../common/js/fetch";

class ImportFile extends Component {
    constructor(props) {
        super(props);
        // console.log(props, 'props');
        this.state = {
            fileName: '',
            isUpload: false,
            uploadFinish: false,
            uploadData: {},
            isFail: false,
        }
    }

    // 选择文件
    openFileUploader = () => {
        document.getElementById('fileInput').click();
    }

    cancelLead = (type) => {
        this.setState({
            isUpload: false,
            uploadFinish: false,
            fileName: '',
        }, () => {
            if (type === 'finish') {
                this.props.getWeekDetail()
            }
            // 清空input选择的文件
            document.getElementById('fileInput').value = '';
            this.props.closeImport();
        })
    }

    // 重新导入
    reimport = () => {
        document.getElementById('fileInput').value = '';
        this.setState({
            isUpload: false,
            uploadFinish: false,
            fileName: '',
        })
    }

    // 文件输入框变化事件处理函数
    handleFileChange = (event) => {
        const file = event.target.files[0];
        if (file) {
            const fileName = file.name;
            this.setState({
                fileName
            })
            // 在这里可以使用文件名称进行后续操作，例如显示文件名等
            console.log('选取的文件名称:', fileName);
        }
    }

    // 值周/值日安排导入
    importTemplate = () => {
        let { weekDetail, userInfo, termInfo } = this.props;
        let fileInput = document.getElementById('fileInput');
        let file = fileInput.files[0];
        let baseUrl = JSON.parse(sessionStorage.getItem('schoolSystemInfo')).itemUrl;
        // let baseUrl = window._noticeBasicProxy;
        if (file) {
            let formData = new FormData();
            formData.append('file', file);
            formData.append('schoolId', userInfo.schoolId);
            formData.append('semester', termInfo.term);
            formData.append('arrangementId', weekDetail.arrangementId);

            this.setState({
                isUpload: true,
            }, () => {
                let xhr = new XMLHttpRequest();
                xhr.open('POST', baseUrl + '/api/dw/v2/import/weekOrDayPlayImport');
                xhr.setRequestHeader('Authorization', sessionStorage.getItem('token'));
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === XMLHttpRequest.DONE) {
                        if (xhr.status === 200) {
                            let response = JSON.parse(xhr.responseText);
                            if (response.code == 200 && response.data != false) {
                                this.setState({
                                    isUpload: false,
                                    uploadFinish: true,
                                    isFail: false,
                                    uploadData: response.data,
                                });
                            } else {
                                // message.error(response.msg, 3);
                                this.setState({
                                    isFail: true,
                                    uploadFinish: true,
                                    isUpload: false,
                                })
                                message.error('导入失败', 3);
                            }
                        } else {
                            let result = JSON.parse(xhr.responseText);
                            this.setState({
                                isFail: true,
                                uploadFinish: true,
                                isUpload: false,
                            })
                            // console.log(result, 'xhr');
                            message.error(result.msg, 3);
                        }
                    }
                };

                xhr.send(formData);
            });
        } else {
            message.warn('请先选择文件');
        }
    };

    downloadFailFile = () => {
        let { weekDetail, userInfo, termInfo } = this.props;
        getData("/api/dw/v2/import/weekOrDayPlayImport/resultExcel", {
            schoolId: userInfo.schoolId,
            semester: termInfo.term,
            arrangementId: weekDetail.arrangementId,
        })
            .then((res) => {
                if (res.ok) {
                    return (res.blob());
                } else {
                    throw new Error('下载失败，请重试！');
                }
            })
            .then((blob) => {
                // 创建下载链接
                let downloadUrl = URL.createObjectURL(blob);

                // 创建 <a> 元素并设置下载链接
                let link = document.createElement('a');
                link.href = downloadUrl;
                let fileName = 'template.xls';
                let templateId = weekDetail.templateId;

                if (weekDetail.typeOf === '1') {
                    if (templateId.includes("week_1")) {
                        fileName = '标准值周导入结果（错误项详情）.xls'
                    } else {
                        fileName = '极简值周导入结果（错误项详情）.xls'
                    }
                } else {
                    if (templateId.includes("day_1")) {
                        fileName = '轮流值日导入结果（错误项详情）.xls'
                    } else if (templateId.includes("day_2")) {
                        fileName = '常规值日导入结果（错误项详情）.xls'
                    } else {
                        fileName = '职责明确值日导入结果（错误项详情）.xls'
                    }
                }

                link.download = fileName; // 设置下载文件名

                // 模拟点击下载
                link.click();

                // 释放下载链接资源
                URL.revokeObjectURL(downloadUrl);
                this.setState({
                    downLoading: false
                })
            })
    }
    render() {
        const {
            isOpen,
            title,
            downloadTemplate,
        } = this.props
        let {
            fileName,
            isUpload,
            uploadFinish,
            uploadData,
            isFail,

        } = this.state
        return (
            <div>
                <LgPopLayer
                    className='lead_into_pop'
                    title={title}
                    confirmText={'确定'}
                    cancelText="取消"
                    centered
                    width='800px'
                    height='360px'
                    maskClosable={false}
                    isOpen={isOpen}
                    onIconClose={() => { this.cancelLead() }}
                    rootScroll={false}
                    isShowBottom={false}
                >
                    <div className='lead_into_div'>
                        <div className='lead_into_top'>
                            <div className='a_key_progress'>
                                <div className={'progress_1 ' + (isUpload || uploadFinish ? 'progress_finish' : 'progress_active')}>1.提交值日安排文件</div>
                                <div className={'progress_2 ' + (isUpload || uploadFinish ? 'progress_finish' : '')}>2.导入文件</div>
                                <div className={'progress_3 ' + (isUpload ? 'progress_active' : uploadFinish ? 'progress_finish' : '')}>3.执行导入</div>
                                <div className={'progress_4 ' + (uploadFinish ? 'progress_finish' : '')}>4.导入结果</div>
                            </div>
                        </div>
                        <div className='lead_into_middle'>
                            {
                                isUpload ?
                                    <div className='loading_div'>
                                        <LgLoadingCircleRotation text={'正在处理~'} />
                                    </div>
                                    :
                                    uploadFinish ?
                                        isFail ?
                                            <div className='upload_results'>
                                                <i className='upload_fail'></i>
                                                <div>导入失败
                                                    <span className='download_excel' onClick={() => this.downloadFailFile()}>下载失败文件</span>
                                                    {/* <div>成功导入{uploadData.successCount}条，失败{uploadData.failCount}条。 */}
                                                    {/* 点击 <LgButton type='info' shapeType='text' onClick={() => this.downloadImportResultExcel()}>下载失败列表</LgButton> */}
                                                </div>
                                            </div>
                                            :
                                            <div className='upload_results'>
                                                <i className='upload_success'></i>
                                                <div>导入成功</div>
                                                {/* <div>成功导入{uploadData.successCount}条，失败{uploadData.failCount}条。</div> */}
                                            </div>
                                        :
                                        <>
                                            <div className='tips_icon_div'>
                                                <i className='tips_icon'></i>
                                                <span>操作提示</span>
                                            </div>
                                            <div>建议用系统提供的模板，请点击下载"<LgButton type='info' shapeType='text' onClick={() => downloadTemplate()}>模板</LgButton>"。</div>
                                        </>
                            }
                        </div>
                        <div className='lead_into_bottom'>
                            <input onChange={this.handleFileChange} accept=".xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" type="file" id="fileInput" style={{ display: 'none' }} />
                            {
                                isUpload ?
                                    ''
                                    :
                                    uploadFinish ?
                                        isFail ?
                                            <div className='btn_bottom'>
                                                <LgButton backgroundType='opacification' gradient radius type='info' onClick={() => this.reimport()}>重新导入</LgButton>
                                            </div>
                                            :
                                            <div className='btn_bottom'>
                                                <LgButton backgroundType='opacification' gradient radius type='info' onClick={() => this.cancelLead('finish')}>确定</LgButton>
                                            </div>
                                        :
                                        <><div className='btn_top'>
                                            <div className='btn_border_div' onClick={() => this.openFileUploader()}>
                                                <div className='btn_border'><div title={fileName} className='file_name'>{fileName}</div></div>
                                                <LgButton className='button_wrapper' backgroundType='translucent' border type='info'>浏览</LgButton>
                                            </div>
                                        </div>
                                            <div className='btn_bottom'>
                                                <LgButton backgroundType='opacification' gradient radius type='info' onClick={() => this.importTemplate()}>提交上传</LgButton>
                                            </div></>
                            }
                        </div>
                    </div>
                </LgPopLayer>
            </div>
        )
    }
}

export default ImportFile;